package com.rc.saas.mini.controller.member;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.common.constant.SessionConstants;
import com.rc.saas.mini.common.utils.BeanUtil;
import com.rc.saas.mini.component.RedisLoader;
import com.rc.saas.mini.minip.token.RedisTokenLoader;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.car.TenantCarNumber;
import com.rc.saas.mini.model.car.TenantCarNumberExample;
import com.rc.saas.mini.model.enterprise.EnterpriseSubmemberApply;
import com.rc.saas.mini.model.enterprise.EnterpriseSubmemberApplyExample;
import com.rc.saas.mini.model.member.*;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.rc.*;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.tenant.TenantTransfer;
import com.rc.saas.mini.model.tenant.TenantTransferExample;
import com.rc.saas.mini.model.tenant.TenantUser;
import com.rc.saas.mini.service.car.TenantCarNumberService;
import com.rc.saas.mini.service.elec.ElecStationCollectService;
import com.rc.saas.mini.service.elec.EnterpriseSubmemberService;
import com.rc.saas.mini.service.enterprise.EnterpriseMemberApplyService;
import com.rc.saas.mini.service.enterprise.EnterpriseSubmemberApplyService;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.member.*;
import com.rc.saas.mini.service.msg.TenantCustomMsgService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.rc.*;
import com.rc.saas.mini.service.recharge.RechargeOrderServiceImpl;
import com.rc.saas.mini.service.tenant.*;
import com.rc.saas.mini.service.ugs.TenantUgsMemberLevelService;
import com.rc.saas.mini.service.ugs.UgsMemberSuperLevelService;
import com.rc.saas.mini.vo.member.*;
import com.rc.saas.mini.vo.rc.RcMemberLevelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wangzhengwei
 * @create 2021/12/15
 */
@Controller
@RequestMapping("/member")
@Api(tags = "05.个人信息相关")
public class MemberController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(MemberController.class);

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private TenantCarNumberService tenantCarNumberService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private MemberMultchargeApplyService memberMultchargeApplyService;

    @Autowired
    private EnterpriseMemberApplyService enterpriseMemberApplyService;

    @Autowired
    private EnterpriseSubmemberApplyService enterpriseSubmemberApplyService;

    @Autowired
    private EnterpriseSubmemberService enterpriseSubmemberService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantCustomMsgService tenantCustomMsgService;

    @Autowired
    private MemberTicketService memberTicketService;

    @Autowired
    private TenantOpenServiceService tenantOpenServiceService;

    @Autowired
    private TenantUgsMemberLevelService tenantUgsMemberLevelService;

    @Autowired
    private UgsMemberSuperLevelService ugsMemberSuperLevelService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ElecStationCollectService elecStationCollectService;

    @Autowired
    private RcChannelApplyService rcChannelApplyService;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private RcMemberFlagService rcMemberFlagService;

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private TenantNoticeService tenantNoticeService;
    @Autowired
    private RechargeOrderServiceImpl rechargeOrderServiceImpl;
    @Autowired
    private RcMemberLevelSettingService rcMemberLevelSettingService;
    @Autowired
    private MemberAccountRecordService memberAccountRecordService;
    @Autowired
    private RcChannelApplyServiceImpl rcChannelApplyServiceImpl;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private RcOperatorService rcOperatorService;

    @Autowired
    private RcNoticeNotificationService rcNoticeNotificationService;

    @Autowired
    private MemberRefundApplyService memberRefundApplyService;

    @Autowired
    private TenantTransferService tenantTransferService;

    @Autowired
    private RedisTokenLoader redisTokenLoader;

    /**
     * 获取当前用户权益信息
     */
    @ResponseBody
    @RequestMapping("/selectChannelCenterVo")
    @ApiOperation(value = "渠道中心", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<ChannelCenterVo> selectChannelCenterVo(HttpServletRequest request) {
        ChannelCenterVo channelCenterVo = new ChannelCenterVo();

        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(member.getMemberId());
        logger.info("MemberController.selectMember.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        BeanUtils.copyProperties(memberAccount, channelCenterVo);

        RcChannelApply rcChannelApply = rcChannelApplyService.selectByUsingMemberId(member.getMemberId());
        if (rcChannelApply != null) {
            channelCenterVo.setChannelName(rcChannelApply.getChannelName());
        }


        MemberInfoExample memberInfoExample = new MemberInfoExample();
        memberInfoExample.createCriteria().andRecommenderIdEqualTo(loginInfo.getMemberId());
        List<MemberInfo> memberInfoList = memberInfoService.selectByExample(memberInfoExample);

        MemberAccountRecordExample memberAccountRecordExample = new MemberAccountRecordExample();
        memberAccountRecordExample.createCriteria().andMemberIdEqualTo(member.getMemberId()).andAccountTypeEqualTo("3").andRecordTypeEqualTo("0");
        List<MemberAccountRecord> memberAccountRecordList = memberAccountRecordService.selectByExample(memberAccountRecordExample);

        channelCenterVo.setMemberSum(memberInfoList.size());
        channelCenterVo.setOrderNums(memberAccountRecordList.size());
        channelCenterVo.setAllTransferAmount(channelCenterVo.getAllIncomeAmount().subtract(channelCenterVo.getIncomeAmount()));
        return DataTResponse.SUCCESS_DATA(channelCenterVo);
    }

    /**
     * 我的账户->账户记录
     */
    @ResponseBody
    @RequestMapping("/listPageAccount")
    @ApiOperation(value = "渠道中心-账户记录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNo", paramType = "query", value = "", required = false), @ApiImplicitParam(name = "pageSize", paramType = "query", value = "", required = false)})
    public DataTResponse<PageInfo<MemberAccountRecord>> listPageAccount(HttpServletRequest request, @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        String tenantCode = loginInfo.getTenantCode();
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }

        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        logger.info("MemberAccountController.listPageAccountDate.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        PageHelper.startPage(pageNo, pageSize);
        MemberAccountRecordExample memberAccountRecordExample = new MemberAccountRecordExample();
        memberAccountRecordExample.createCriteria().andMemberIdEqualTo(member.getMemberId()).andAccountTypeEqualTo("3");
        memberAccountRecordExample.setOrderByClause("created_time desc");
        List<MemberAccountRecord> memberAccountRecordList = memberAccountRecordService.selectByExample(memberAccountRecordExample);
        PageInfo<MemberAccountRecord> pageInfo = new PageInfo<>(memberAccountRecordList);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }

    /**
     * 获取当前用户权益信息
     */
    @ResponseBody
    @RequestMapping("/selectCurrentMemberFlagAllVo")
    @ApiOperation(value = "03.获取当前用户权益信息(全部)", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<CurrentMemberFlagAllVo> selectCurrentMemberFlagAllVo(HttpServletRequest request) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
        logger.info("MemberController.selectMember.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        return DataTResponse.SUCCESS_DATA(currentMemberFlagAllVo);
    }

    /**
     * 获取当前用户权益信息
     */
    @ResponseBody
    @RequestMapping("/selectMemberCenterVo")
    @ApiOperation(value = "04.会员中心", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<MemberCenterVo> selectMemberCenterVo(HttpServletRequest request) {
        MemberCenterVo memberCenterVo = new MemberCenterVo();

        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(member.getMemberId());
        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
        logger.info("MemberController.selectMember.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        List<OrderInfo> orderInfoList = orderInfoService.listFinishOrder(member.getMemberId());
        RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(member.getMemberId());
        //update vo upamount
        if (rcMemberFlag.getSubLevel() != null && "V0".equals(rcMemberFlag.getSubLevel())) {
            MemberAccount memberAccount1 = new MemberAccount();
            memberAccount1.setMemberId(member.getMemberId());
            memberAccount1.setUpperAmount(BigDecimal.ZERO);
            memberAccountService.updateByPrimaryKeySelective(memberAccount1);
        }
        RcMemberLevelSetting next = rcMemberLevelSettingService.selectByNext(member);

        memberCenterVo.setCurrentMemberFlagAllVo(currentMemberFlagAllVo);
        memberCenterVo.setAllGiveAmount(memberAccount.getSaveAmount());
        memberCenterVo.setAllRechargeAmount(memberAccount.getAllRechargeAmount());
        memberCenterVo.setOrderNums(orderInfoList.size());
        memberCenterVo.setUpperAmount(memberAccount.getUpperAmount());
        if (next != null) {
            memberCenterVo.setNextMemberLevel(next.getMemberLevel());
            memberCenterVo.setNextMoney(next.getRechargeAmountTarget());
        }
        if (next == null && currentMemberFlagAllVo != null && currentMemberFlagAllVo.getRcMemberLevelVo() != null) {
            memberCenterVo.setNextMemberLevel(currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberLevelSetting().getMemberLevel());
            memberCenterVo.setNextMoney(currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberLevelSetting().getRechargeAmountTarget());
        }
        return DataTResponse.SUCCESS_DATA(memberCenterVo);
    }

    /**
     * 获取当前默认配置用户权益信息
     */
    @ResponseBody
    @RequestMapping("/selectMemberFlagAllVo")
    @ApiOperation(value = "04.获取当前默认配置用户权益信息", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "type", paramType = "query", value = "默认0 0全部，1会员权益，2企业权益，3渠道商权益", required = true)})
    public DataTResponse<MemberFlagAllVo> selectMemberFlagAllVo(HttpServletRequest request, @RequestParam(value = "type", defaultValue = "0") int type) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberFlagAllVo memberFlagAllVo = rcMemberFlagService.selectMemberFlagAllVo(member, type);
        logger.info("MemberController.selectMember.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        return DataTResponse.SUCCESS_DATA(memberFlagAllVo);
    }

    /**
     * 获取个人信息
     */
    @ResponseBody
    @RequestMapping("/profile")
    @ApiOperation(value = "01.获取个人信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public DataTResponse<ProfileVo> profile(HttpServletRequest request) {
        ProfileVo profileVo = new ProfileVo();
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        rcMemberFlagService.updateByEnterprise(member.getMemberId());
        logger.info("MemberController.profile.tenantCode:{},mobile:{}", tenantCode, member.getMobile());
        RcChannelApplyExample rcChannelApplyExample = new RcChannelApplyExample();
        rcChannelApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
        rcChannelApplyExample.setOrderByClause("created_time desc");
        List<RcChannelApply> rcChannelApplyList = rcChannelApplyService.selectByExample(rcChannelApplyExample);
        if (rcChannelApplyList.size() > 0) {
            profileVo.setChannelType(rcChannelApplyList.get(0).getApplyStatus());
        }
        //EnterpriseMemberApplyExample enterpriseMemberApplyExample=new EnterpriseMemberApplyExample();
        //enterpriseMemberApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
        //enterpriseMemberApplyExample.setOrderByClause("created_time desc");
        //List<EnterpriseMemberApply> enterpriseMemberApplyList=enterpriseMemberApplyService.selectByExample(enterpriseMemberApplyExample);

        EnterpriseSubmemberApplyExample enterpriseSubMemberApplyExample = new EnterpriseSubmemberApplyExample();
        enterpriseSubMemberApplyExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
        enterpriseSubMemberApplyExample.setOrderByClause("created_time desc");
        List<EnterpriseSubmemberApply> enterpriseSubmemberApplyList = enterpriseSubmemberApplyService.selectByExample(enterpriseSubMemberApplyExample);
        if (enterpriseSubmemberApplyList.size() > 0) {
            profileVo.setEnterpriseType(enterpriseSubmemberApplyList.get(0).getApplyStatus());
        }

        RcOperatorExample rcOperatorExample = new RcOperatorExample();
        rcOperatorExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
        rcOperatorExample.setOrderByClause("created_time desc");
        List<RcOperator> rcOperatorList = rcOperatorService.selectByExample(rcOperatorExample);
        if (rcOperatorList.size() > 0) {
            profileVo.setOperatorType(rcOperatorList.get(0).getStatus());
        }


        try {
            //存储个人信息表单,车型选择页面后可以记录
            Map<String, String> memberInfo = new HashMap<>();
            memberInfo.put("nickname", member.getNickname());
            memberInfo.put("sex", member.getSex());
            memberInfo.put("birthday", member.getBirthday() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(member.getBirthday()));

            //得到默认车牌号
            TenantCarNumber defultCarNum = tenantCarNumberService.selectDefaultCarNumber(loginInfo.getMemberId());
            if (defultCarNum != null) {
                memberInfo.put("carType", defultCarNum.getCarType());
                memberInfo.put("carArea", defultCarNum.getCarArea());
                memberInfo.put("carLetter", defultCarNum.getCarLetter());
                memberInfo.put("carNum", defultCarNum.getCarNum());
            } else {
                memberInfo.put("carType", null);
                memberInfo.put("carArea", null);
                memberInfo.put("carLetter", null);
                memberInfo.put("carNum", null);
            }
            //session.setAttribute("memberInfo", memberInfo);
            //getRedisTokenLoader().updateToken(g)
            //会员账户信息
            MemberAccountExample example = new MemberAccountExample();
            example.createCriteria().andTenantCodeEqualTo(tenantCode).andMemberIdEqualTo(member.getMemberId());
            List<MemberAccount> memberAccounts = memberAccountService.selectByExample(example);


            Map memberMap = new HashMap();
            if (memberAccounts != null && memberAccounts.size() > 0) {
                //memberMap.put("memberAccounts", memberAccounts.get(0));
                profileVo.setMemberAccount(memberAccounts.get(0));
            } else {
                //memberMap.put("memberAccounts", new MemberAccount());
                profileVo.setMemberAccount(new MemberAccount());
            }
            //

            //memberMap.put("member", member);
            RcMemberFlag rcMemberFlag = rcMemberFlagService.selectByPrimaryKey(member.getMemberId());
            //if(rcMemberFlag==null||rcMemberFlag.getMemberLevel()==null){
            //    //增加默认会员等级
            //    rechargeOrderServiceImpl.rcMemberLevelSettingAdd(profileVo.getMemberAccount());
            //}


            //渠道商升级
            rcChannelApplyServiceImpl.updateRcChannelApplyByMember(member.getMemberId());
            profileVo.setMember(member);
            //会员等级
            //渠道商
            //企业会员
            CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
            //删掉冗余数据
            if (currentMemberFlagAllVo.getRcMemberLevelVo() != null) {

                currentMemberFlagAllVo.getRcMemberLevelVo().setRcMemberGainSettingRecordVos(null);
            }
            if (currentMemberFlagAllVo.getRcEnterpriseLevelVo() != null) {
                profileVo.setEnterpriseType("1");
                currentMemberFlagAllVo.getRcEnterpriseLevelVo().setRcEnterpriseGainRecordVos(null);
            }
            if (currentMemberFlagAllVo.getRcChannelLevelVo() != null) {
                profileVo.setChannelType("1");
                currentMemberFlagAllVo.getRcChannelLevelVo().setRcChannelGainRecords(null);
            }
            if (currentMemberFlagAllVo.getRcOperator() != null) {
                profileVo.setOperatorType("1");

            }
            //用户当前权益
            //memberMap.put("memberFlagAllVo", currentMemberFlagAllVo);
            profileVo.setCurrentMemberFlagAllVo(currentMemberFlagAllVo);
            //获取运营商客服电话
            Tenant tenant = tenantService.selectByTenantCode(tenantCode);
            //memberMap.put("servicePhone", tenant.getServicePhone());
            profileVo.setServicePhone(tenant.getServicePhone());
            //判断是否有新消息  !0 是  0  否
            //TenantNoticeVo tenantNotice = new TenantNoticeVo();
            //tenantNotice.setStatus("1");
            //tenantNotice.setMemberId(member.getMemberId());

            rcNoticeNotificationService.addNotice(member.getMemberId());

            List<RcNoticeNotification> rcNoticeNotificationList = rcNoticeNotificationService.listByMemberId(member.getMemberId());
            List<RcNoticeNotification> msgList = rcNoticeNotificationList.stream().filter(data -> "0".equals(data.getIsRead())).collect(Collectors.toList());
            //List<TenantNoticeVo> list = tenantNoticeService.listByConditionWithMemberId(tenantNotice);
            //TenantCustomMsgExample tenantCustomMsgExample = new TenantCustomMsgExample();
            //tenantCustomMsgExample.createCriteria().andTenantCodeEqualTo(tenantCode).andMsgTypeEqualTo("1").andIsReadEqualTo("0").andMemberIdEqualTo(member.getMemberId());
            //Long count = list.stream().filter(data -> "0".equals(data.getIsRead())).count();
            //memberMap.put("isNewMsg", count);
            profileVo.setIsNewMsg(String.valueOf(msgList.size()));
            //车牌数
            TenantCarNumberExample tenantCarNumberExample = new TenantCarNumberExample();
            tenantCarNumberExample.createCriteria().andMemberIdEqualTo(member.getMemberId());
            Long countCarnum = tenantCarNumberService.countByExample(tenantCarNumberExample);
            //memberMap.put("countCarnum", countCarnum);
            profileVo.setCountCarnum(String.valueOf(countCarnum));
            //优惠券数
            MemberTicketExample memberTicketExample = new MemberTicketExample();
            memberTicketExample.createCriteria().andMemberIdEqualTo(member.getMemberId()).andStatusEqualTo("0").andEndTimeGreaterThan(new Date());
            Long countTicket = memberTicketService.countByExample(memberTicketExample);
            //memberMap.put("countTicket", countTicket);
            profileVo.setCountTicket(String.valueOf(countTicket));

            //DataTResponse DataTResponse = DataTResponse.SUCCESS();
            //DataTResponse.put(memberMap);
            redisLoader.opsForValueSet(loginInfo.getToken(), loginInfo, 360, TimeUnit.HOURS);
            return DataTResponse.SUCCESS_DATA(profileVo);

        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e);
            return DataTResponse.FAIL();
        }
    }

    /**
     * 修改个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/updateProfile", method = RequestMethod.POST)
    @ApiOperation(value = "02.修改个人信息(需要登陆)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "nickname", paramType = "query", value = "昵称", required = true), @
            ApiImplicitParam(name = "sex", paramType = "query", value = "性别（0未确定 1男 2女）", required = true),
            @ApiImplicitParam(name = "birth", paramType = "query", value = "生日", required = true),
            @ApiImplicitParam(name = "recommenderId", paramType = "query", value = "推荐人ID", required = false),
            @ApiImplicitParam(name = "mobile", paramType = "query", value = "手机号", required = false),
            @ApiImplicitParam(name = "authCode", paramType = "query", value = "验证码", required = false),
            @ApiImplicitParam(name = "headImg", paramType = "query", value = "头像", required = false),
            @ApiImplicitParam(name = "nameReal", paramType = "query", value = "阿里真实昵称", required = false),
            @ApiImplicitParam(name = "unionid", paramType = "query", value = "小程序unionid", required = false),
            @ApiImplicitParam(name = "openid", paramType = "query", value = "小程序openid", required = false)})
    public DataTResponse<String> updateProfile(HttpServletRequest request, String nickname, String sex, String birth,
                                               String headImg, String recommenderId, String mobile, String authCode,
                                               String nameReal, String unionid, String openid) throws Exception {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());

        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        if (unionid != null && unionid.length() > 0) {

            MemberInfo memberInfoOld = memberInfoService.selectMemberByUnionid(unionid, tenantCode);
            if (memberInfoOld != null && memberInfoOld.getMemberId() != loginInfo.getMemberId()) {
                return DataTResponse.FAIL("该微信账号已绑定其他瑞晨云充账号");
            }
            if (memberInfoOld == null) {
                Tenant tenant = tenantService.selectByTenantCode(tenantCode);
                member.setMinipOpenid(openid);
                member.setWechatUnionid(unionid);
                member.setMinipOriginalid(tenant.getMinipOriginalid());

                loginInfo.setMiniOpenid(openid);
                loginInfo.setMiniUnionid(unionid);
                loginInfo.setTenantCode(tenant.getTenantCode());
                loginInfo.setMiniOriginalid(tenant.getMinipOriginalid());
                redisTokenLoader.updateToken(loginInfo.getToken(), loginInfo);

            }

        }
        logger.info("MemberController.updateProfile.tenantCode:{},mobile:{}", tenantCode, member.getMobile());


        //换绑手机功能
        if (mobile != null && authCode != null) {
            if (!BeanUtil.isValid(mobile, authCode)) {
                return DataTResponse.FAIL("有选项未填写");
            }
            //        mobile = SecurityTool.decodeDES(mobile);
            if (!mobile.matches(HttpConstant.MOBILE_REGEX)) {
                return DataTResponse.FAIL("手机号码格式不正确");
            }

            MemberInfo memberInfoOld = memberInfoService.selectByMobile(mobile, tenantCode);


            if (memberInfoOld != null && memberInfoOld.getMemberId() != loginInfo.getMemberId()) {
                //情况1.当前用户有第三方无手机号（支付宝），且旧数据有
                if (memberInfoOld.getAliUserId() != null && loginInfo.getAliUserId() != null && loginInfo.getMobile() == null) {
                    return DataTResponse.FAIL("该手机号已绑定其他支付宝账号");
                }
                //情况2.当前用户有第三方无手机号（weixin），且旧数据有
                if (memberInfoOld.getWechatOpenid() != null && loginInfo.getWechatOpenid() != null && loginInfo.getMobile() == null) {
                    return DataTResponse.FAIL("该手机号已绑定其他微信账号");
                }
                //情况3.当前用户有第三方无手机号（支付宝），且旧数据有手机号无第三方
                if (memberInfoOld.getAliUserId() == null && loginInfo.getAliUserId() != null && loginInfo.getMobile() == null) {
                    MemberInfo memberInfoTemp = member;
                    member=new MemberInfo();
                    BeanUtils.copyProperties(memberInfoOld, member);
                    member.setAliUserId(loginInfo.getAliUserId());

                    //注销掉旧账号
                    Date date=new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateData=sdf.format(date);
                    memberInfoTemp.setWechatUnionid(memberInfoTemp.getWechatUnionid()+"_"+dateData);
                    memberInfoTemp.setWechatOpenid(memberInfoTemp.getWechatOpenid()+"_"+dateData);
                    memberInfoTemp.setMinipOpenid(memberInfoTemp.getMinipOpenid()+"_"+dateData);
                    memberInfoTemp.setAliUserId(memberInfoTemp.getAliUserId()+"_"+dateData);
                    memberInfoTemp.setMobile(memberInfoTemp.getMobile()+"_"+dateData);
                    memberInfoTemp.setLastUpdatedTime(date);
                    memberInfoTemp.setStatus("1");
                    memberInfoTemp.setRemark("用户变更注销");
                    memberInfoService.updateByPrimaryKey(memberInfoTemp);

                }

                //情况4.当前用户有第三方无手机号（微信），且旧数据有手机号无第三方
                if (memberInfoOld.getWechatOpenid() == null && loginInfo.getWechatOpenid() != null && loginInfo.getMobile() == null) {
                    MemberInfo memberInfoTemp = member;
                    member=new MemberInfo();
                    BeanUtils.copyProperties(memberInfoOld, member);
                    member.setWechatOpenid(loginInfo.getWechatOpenid());
                    member.setWechatUnionid(loginInfo.getMiniUnionid());
                    member.setMinipOriginalid(loginInfo.getMiniOriginalid());
                    member.setWechatOriginalid(loginInfo.getMiniOriginalid());


                    //注销掉旧账号
                    Date date=new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateData=sdf.format(date);
                    memberInfoTemp.setWechatUnionid(memberInfoTemp.getWechatUnionid()+"_"+dateData);
                    memberInfoTemp.setWechatOpenid(memberInfoTemp.getWechatOpenid()+"_"+dateData);
                    memberInfoTemp.setMinipOpenid(memberInfoTemp.getMinipOpenid()+"_"+dateData);
                    memberInfoTemp.setAliUserId(memberInfoTemp.getAliUserId()+"_"+dateData);
                    memberInfoTemp.setMobile(memberInfoTemp.getMobile()+"_"+dateData);
                    memberInfoTemp.setLastUpdatedTime(date);
                    memberInfoTemp.setStatus("1");
                    memberInfoTemp.setRemark("用户变更注销");
                    memberInfoService.updateByPrimaryKey(memberInfoTemp);

                }
            }

            //String sessionAuthCode = (String) session.getAttribute(SessionConstants.SESSION_PREFIX_BIND_MOBILE + mobile);
            String sessionAuthCode = redisLoader.opsForValueGet(SessionConstants.SESSION_PREFIX_REGISTER + ":" + mobile, String.class);
            if (!BeanUtil.isValid(sessionAuthCode)) {
                return DataTResponse.FAIL("未申请验证码");
            }
            if (!authCode.equals(sessionAuthCode.substring(0, 6))) {
                return DataTResponse.FAIL("验证码错误");
            }
            //session.removeAttribute(SessionConstants.SESSION_PREFIX_BIND_MOBILE + mobile);
            redisLoader.delete(SessionConstants.SESSION_PREFIX_REGISTER + ":" + mobile);
            if ("1".equals(member.getMemberType())) {
                TenantUser tenantUser = tenantUserService.selectByEnterpriseId(member.getBelongEnterpriseId());
                if (tenantUser != null) {
                    tenantUser.setLoginName(mobile);
                    tenantUserService.updateByPrimaryKeySelective(tenantUser);
                    logger.info("主会员手机换绑成功,oldMobile:{},newMobile:{}", member.getMobile(), mobile);
                }
            }

            member.setMobile(mobile);
            logger.info("手机号码改帮成功,新手机号码:{}", mobile);
        }


        if (headImg != null && !StringUtils.isBlank(headImg)) {
            member.setHeadImg(headImg);
        }
        member.setNickname(nickname);
        if (recommenderId != null && recommenderId.length() > 0) {
            member.setRecommenderId(Long.valueOf(recommenderId));
        }
        member.setNickname2(nickname);
        member.setSex(sex);

        if (nameReal != null && nameReal.length() > 0) {
            member.setNameReal(nameReal);
        }
        if (StringUtils.isNotBlank(birth)) {
            member.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birth));
        }


        memberInfoService.updateByPrimaryKeySelective(member);

        if (member.getRecommenderId() != null) {
            try {
                //渠道商升级
                rcChannelApplyServiceImpl.updateRcChannelApplyByMember(member.getRecommenderId());
                //拉新活动
                marketActivityService.activityAddMember(member.getRecommenderId());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        LoginInfoVo loginInfoNew= convertLoginInfo(member);
        loginInfoNew.setToken(loginInfo.getToken());
        redisLoader.opsForValueSet(loginInfo.getToken(), loginInfoNew, 360, TimeUnit.HOURS);
        return DataTResponse.SUCCESS("修改成功");
    }


    /**
     * 当前金额可获权益金
     */
    @ResponseBody
    @RequestMapping("/getGiveAmountByAmount")
    @ApiOperation(value = "当前金额可获权益金", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "amount", value = "金额", required = true)})
    public DataTResponse<BigDecimal> getGiveAmountByAmount(HttpServletRequest request, BigDecimal amount) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        //成功提现次数
        MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(member.getMemberId());
        List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);

        //提现设置
        TenantTransfer tenantTransfer = tenantTransferService.selectByExample(new TenantTransferExample()).stream().findFirst().orElseGet(() -> null);

        if (tenantTransfer.getTransferNoMoney() <= memberRefundApplyList.size()) {
            logger.info("当前金额可获权益金，memeberId{},提现次数超过设置不享受权益", member.getMemberId(), amount, 0);
            return DataTResponse.SUCCESS_DATA(BigDecimal.ZERO);
        }

        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
        if (currentMemberFlagAllVo.getRcMemberLevelVo() != null) {
            if (currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().size() > 0) {
                RcMemberLevelVo.RcMemberGainSettingRecordVo rcMemberGainSettingRecordVo = currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().stream().filter(data -> "1".equals(data.getRcMemberGainSettingRecord().getGainType())).findFirst().orElseGet(() -> null);
                if (rcMemberGainSettingRecordVo != null) {
                    if (rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().size() > 0) {
                        List<RcMemberGainGradeRecord> list = rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().stream().filter(data -> data.getRechargeAmount() != null && amount.compareTo(data.getRechargeAmount()) >= 0).collect(Collectors.toList());
                        if (list.size() > 0) {
                            RcMemberGainGradeRecord rcMemberGainGradeRecord = list.stream().max(Comparator.comparing(data -> data.getRechargeAmount())).get();
                            if (rcMemberGainGradeRecord != null && rcMemberGainGradeRecord.getGainAmount() != null) {
                                logger.info("当前金额可获权益金，memeberId{},金额{}，权益金{}", member.getMemberId(), amount, rcMemberGainGradeRecord.getGainAmount());
                                return DataTResponse.SUCCESS_DATA(rcMemberGainGradeRecord.getGainAmount());
                            }
                        }

                    }
                }
            }
        }

        logger.info("当前金额可获权益金，memeberId{},金额{}，权益金{}", member.getMemberId(), amount, 0);
        return DataTResponse.SUCCESS_DATA(BigDecimal.ZERO);
    }


    /**
     * 当前金额可获权益金
     */
    @ResponseBody
    @RequestMapping("/getRcMemberGainGradeRecordByAmount")
    @ApiOperation(value = "当前金额可获赠送数据", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "amount", value = "金额", required = true)})
    public DataTResponse<String> getRcMemberGainGradeRecordByAmount(HttpServletRequest request, BigDecimal amount) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        //成功提现次数
        MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(member.getMemberId());
        List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);

        //提现设置
        TenantTransfer tenantTransfer = tenantTransferService.selectByExample(new TenantTransferExample()).stream().findFirst().orElseGet(() -> null);

        if (tenantTransfer.getTransferNoMoney() <= memberRefundApplyList.size()) {
            logger.info("当前金额可获权益金，memeberId{},提现次数超过设置不享受权益", member.getMemberId(), amount, 0);
            return DataTResponse.SUCCESS_DATA("");
        }
        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
        if (currentMemberFlagAllVo.getRcMemberLevelVo() != null) {
            if (currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().size() > 0) {
                RcMemberLevelVo.RcMemberGainSettingRecordVo rcMemberGainSettingRecordVo = currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().stream().findFirst().orElseGet(() -> null);
                if (rcMemberGainSettingRecordVo != null) {
                    if ("0".equals(rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getGainType())) {
                        return DataTResponse.SUCCESS_DATA("充电享" + strs(currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberLevelSetting().getDiscountAmount().multiply(new BigDecimal(10)).toString()) + "折");
                    } else if (rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords() != null && rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().size() > 0) {
                        List<RcMemberGainGradeRecord> list = rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().stream().filter(data -> data.getRechargeAmount() != null && amount.compareTo(data.getRechargeAmount()) >= 0).collect(Collectors.toList());
                        if (list.size() > 0) {
                            RcMemberGainGradeRecord rcMemberGainGradeRecord = list.stream().max(Comparator.comparing(data -> data.getRechargeAmount())).get();
                            if (rcMemberGainGradeRecord != null && (rcMemberGainGradeRecord.getGainAmount() != null || rcMemberGainGradeRecord.getDiscountAmount() != null)) {
                                logger.info("当前金额可获权益金，memeberId{},金额{}，挡位{}", member.getMemberId(), amount, JSON.toJSONString(rcMemberGainGradeRecord));

                                if (rcMemberGainGradeRecord.getGainAmount() != null) {
                                    return DataTResponse.SUCCESS_DATA("赠送权益金" + rcMemberGainGradeRecord.getGainAmount() + "元");
                                }
                            }
                        }
                    }
                    //if (rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords()!=null&&rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().size() > 0) {
                    //    List<RcMemberGainGradeRecord> list = rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords()
                    //            .stream().filter(data -> data.getRechargeAmount() != null && amount.compareTo(data.getRechargeAmount()) >= 0)
                    //            .collect(Collectors.toList());
                    //    if (list.size() > 0) {
                    //        RcMemberGainGradeRecord rcMemberGainGradeRecord = list.stream().max(Comparator.comparing(data -> data.getRechargeAmount())).get();
                    //        if (rcMemberGainGradeRecord != null && (rcMemberGainGradeRecord.getGainAmount() != null || rcMemberGainGradeRecord.getDiscountAmount() != null)) {
                    //            logger.info("当前金额可获权益金，memeberId{},金额{}，挡位{}", member.getMemberId(), amount, JSON.toJSONString(rcMemberGainGradeRecord));
                    //
                    //            if (rcMemberGainGradeRecord.getGainAmount() != null) {
                    //                return DataTResponse.SUCCESS_DATA("赠送权益金" + rcMemberGainGradeRecord.getGainAmount() + "元");
                    //            } else if (rcMemberGainGradeRecord.getDiscountAmount() != null) {
                    //
                    //                return DataTResponse.SUCCESS_DATA("充电享" + rcMemberGainGradeRecord.getDiscountAmount().toString().replaceAll(".00", "") + "折");
                    //            }
                    //        }
                    //    }
                    //
                    //}
                }
            }
        }

        logger.info("当前金额可获权益金，memeberId{},金额{}，权益金{}", member.getMemberId(), amount, 0);
        return DataTResponse.SUCCESS_DATA("");
    }

    /**
     * 当前金额可获权益金
     */
    @ResponseBody
    @RequestMapping("/getRcMemberGainGradeRecordByAmounts")
    @ApiOperation(value = "当前金额可获赠送数据", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "amounts", value = "金额，逗号分割", required = true)})
    public DataTResponse<String> getRcMemberGainGradeRecordByAmounts(HttpServletRequest request, String amounts) {
        String tenantCode = (String) request.getSession().getAttribute(SessionConstants.SESSION_TENANT);
        if (tenantCode == null || StringUtils.isBlank(tenantCode)) {
            logger.error("找不到对应运营商信息:{}", tenantCode);
            return DataTResponse.FAIL("找不到对应运营商信息");
        }
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        //成功提现次数
        MemberRefundApplyExample memberRefundApplyExample = new MemberRefundApplyExample();
        memberRefundApplyExample.createCriteria().andStatusEqualTo("4").andMemberIdEqualTo(member.getMemberId());
        List<MemberRefundApply> memberRefundApplyList = memberRefundApplyService.selectByExample(memberRefundApplyExample);

        //提现设置
        TenantTransfer tenantTransfer = tenantTransferService.selectByExample(new TenantTransferExample()).stream().findFirst().orElseGet(() -> null);


        CurrentMemberFlagAllVo currentMemberFlagAllVo = rcMemberFlagService.selectCurrentMemberFlagAllVo(member);
        List<String> endData = new ArrayList<>();
        Arrays.asList(amounts.split(",")).forEach(id -> {
            BigDecimal amount = new BigDecimal(id);
            //成功提现次数

            if (tenantTransfer.getTransferNoMoney() <= memberRefundApplyList.size()) {
                endData.add("");
            } else if (currentMemberFlagAllVo.getRcMemberLevelVo() != null) {
                if (currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().size() > 0) {
                    RcMemberLevelVo.RcMemberGainSettingRecordVo rcMemberGainSettingRecordVo = currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberGainSettingRecordVos().stream().filter(data -> !"3".equals(data.getRcMemberGainSettingRecord().getGainType())).findFirst().orElseGet(() -> null);

                    if (rcMemberGainSettingRecordVo != null) {
                        //充电享受折扣
                        if ("0".equals(rcMemberGainSettingRecordVo.getRcMemberGainSettingRecord().getGainType())) {
                            endData.add("充电享" + strs(currentMemberFlagAllVo.getRcMemberLevelVo().getRcMemberLevelSetting().getDiscountAmount().multiply(new BigDecimal(10)).toString()) + "折");
                        } else if (rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().size() > 0) {
                            List<RcMemberGainGradeRecord> list = rcMemberGainSettingRecordVo.getRcMemberGainGradeRecords().stream().filter(data -> data.getRechargeAmount() != null && amount.compareTo(data.getRechargeAmount()) >= 0).collect(Collectors.toList());
                            if (list.size() > 0) {
                                RcMemberGainGradeRecord rcMemberGainGradeRecord = list.stream().max(Comparator.comparing(data -> data.getRechargeAmount())).get();
                                if (rcMemberGainGradeRecord != null && (rcMemberGainGradeRecord.getGainAmount() != null || rcMemberGainGradeRecord.getDiscountAmount() != null)) {
                                    logger.info("当前金额可获权益金，memeberId{},金额{}，挡位{}", member.getMemberId(), amount, JSON.toJSONString(rcMemberGainGradeRecord));

                                    if (rcMemberGainGradeRecord.getGainAmount() != null) {
                                        endData.add("赠送权益金" + rcMemberGainGradeRecord.getGainAmount() + "元");
                                    }
                                    //else if (rcMemberGainGradeRecord.getDiscountAmount() != null) {
                                    //
                                    //}
                                    else {
                                        endData.add("");
                                    }
                                } else {
                                    endData.add("");
                                }
                            } else {
                                endData.add("");
                            }

                        } else {
                            endData.add("");
                        }
                    } else {
                        endData.add("");
                    }
                } else {
                    endData.add("");
                }
            }
        });


        logger.info("当前金额可获权益金，memeberId{},金额{}，权益金{}", member.getMemberId(), endData, 0);
        return DataTResponse.SUCCESS_DATA(endData);
    }

    //去掉尾数
    private static String strs(String str) {
        if (str.indexOf(".") > 0) {
            str = str.replaceAll("0+?$", "");//删掉尾数为0的字符
            str = str.replaceAll("[.]$", "");//结尾如果是小数点，则去掉
        }
        return str;

        // TODO Auto-generated method stub
    }

    /**
     * 创建LoginInfo对象
     *
     * @param member
     * @return
     */
    private LoginInfoVo convertLoginInfo(MemberInfo member) {
        LoginInfoVo newLoginInfo = new LoginInfoVo();
        //运营商，必需
        newLoginInfo.setTenantCode(member.getTenantCode());
        newLoginInfo.setMemberId(member.getMemberId());
        newLoginInfo.setNickname(member.getNickname());
        newLoginInfo.setNickname2(member.getNickname2());
        newLoginInfo.setMobile(member.getMobile());
        newLoginInfo.setHeadImg(member.getHeadImg());
        newLoginInfo.setSex(member.getSex());
        newLoginInfo.setBirthday(member.getBirthday());
        newLoginInfo.setWechatOpenid(member.getWechatOpenid());
        newLoginInfo.setMiniOpenid(member.getMinipOpenid());
        newLoginInfo.setMiniUnionid(member.getWechatUnionid());
        newLoginInfo.setAliUserId(member.getAliUserId());
        String carNum = null;
        if (StringUtils.isNotBlank(member.getCarArea())) {
            carNum = member.getCarArea();
        }
        if (StringUtils.isNotBlank(member.getCarLetter())) {
            carNum = carNum + member.getCarLetter();
        }
        if (StringUtils.isNotBlank(member.getCarNumber())) {
            carNum = carNum + member.getCarNumber();
        }

        newLoginInfo.setCarNumber(carNum);
        newLoginInfo.setMemberType(member.getMemberType());
        //
        //MemberInfo memberInfo=new MemberInfo();
        //memberInfo.setMemberId(member.getMemberId());
        //memberInfo.setLastLoginTime(new Date());
        memberInfoService.updateLogin(member.getMemberId());


        newLoginInfo.setLastPlatformMsgTime(member.getLastPlatformMsgTime());
        newLoginInfo.setLastCustomMsgTime(member.getLastCustomMsgTime());

        return newLoginInfo;
    }
}
